#include <REGX52.H>
#include <INTRINS.H>
#include "Delay.h"
#include "Key.h"
#include "timer0.h"
#include "LCD1602.h"
#include "Nixie.h"
#include "AT24c02.h"

unsigned char Minute;
unsigned char Second;
unsigned char HunSecond;
unsigned char Second_Enable = 1;

void main()
{
	unsigned char Key_Num = 0;
	unsigned char Byte = 0;
	unsigned int i = 0;
	
	
	Timer0_Init();
	P2 = 0xff;
	//LCD_Init();
	
	//LCD_ShowString(1,1,"Hello!");
	

	
	Nixie_Setbuffer(1, 0);
	Nixie_Setbuffer(2, 0);
	Nixie_Setbuffer(3, 10);
	Nixie_Setbuffer(4, 0);
	Nixie_Setbuffer(5, 0);
	Nixie_Setbuffer(6, 10);
	Nixie_Setbuffer(7, 0);
	Nixie_Setbuffer(8, 0);
	
	Minute = AT24c02_ReadByte(0x00);
	Second = AT24c02_ReadByte(0x01);
	HunSecond = AT24c02_ReadByte(0x02);
	
	
	while(1)
	{
		Key_Num = Key();
		if(Key_Num == 1){
			Second_Enable = !Second_Enable;
		}
		if(Key_Num == 2){
			AT24c02_WriteByte(0x00, Minute);
			Delay(5);
			AT24c02_WriteByte(0x01, Second);
			AT24c02_WriteByte(0x02, HunSecond);
			
			//LCD_Init();
			//LCD_ShowString(1,1,"Saving Data");
			//Delay(1000);
			//LCD_Init();
			
		}
		if(Key_Num == 2){
			Minute = AT24c02_ReadByte(0x00);
			Second = AT24c02_ReadByte(0x01);
			HunSecond = AT24c02_ReadByte(0x02);
			
			//LCD_Init();
			//LCD_ShowString(1,1,"Read Data");
			//Delay(1000);
			//LCD_Init();
			
		}
		
		//更新数码管显示数组
		Nixie_Setbuffer(1, HunSecond%10);
		Nixie_Setbuffer(2, HunSecond/10);
		Nixie_Setbuffer(3, 10);
		Nixie_Setbuffer(4, Second%10);
		Nixie_Setbuffer(5, Second/10);
		Nixie_Setbuffer(6, 10);
		Nixie_Setbuffer(7, Minute%10);
		Nixie_Setbuffer(8, Minute/10);
	}
}


/**
  * @brief  定时器0中断处理函数模版
  * @param  无
  * @retval 无
  */
void Timer_Routine(void) interrupt 1
{
	static unsigned int key_count = 0;
	static unsigned int nixie_count = 0;
	static unsigned int sec_count = 0;
	
	TR0 = 0;
	
	key_count++;
	if(key_count >= 20)
	{
		Key_Loop();
		key_count = 0;		
	}
	
	
	nixie_count++;
	if(nixie_count >= 2)
	{
		Nixie_Loop();
		nixie_count = 0;		
	}
	
	
		
	sec_count++;
	if(sec_count >= 10)		//10ms
	{
		sec_count = 0; 		//10ms counter
		
		
		if(Second_Enable)
		{
			HunSecond++;
			if(HunSecond >= 100)
			{
				HunSecond = 0;
				Second++;
			}
			if(Second >= 60)
			{
				Second = 0;
				Minute++;
			}
			if(Minute >= 60)
			{
				Minute = 0;
			}
		}

	}
		
	//定时器溢出之后需要重新装载
	TH0 = (65535 - 1000) / 256;					//12MHz晶振，12分频
	TL0 = (65535 - 1000) % 256 + 1; 			//
	
	TR0 = 1;
}